﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class UserSetController : Controller
    {
        /// <summary>
        /// 用户签章
        /// </summary>
        /// <returns></returns>
        [Validate]
        public IActionResult Sign()
        {
            string webPath = Current.WebRootPath;
            var user = Current.User;
            string signPath = webPath + "/RoadFlowResources/images/userSigns/" + user.Id.ToUpperString();
            DirectoryInfo directoryInfo = new DirectoryInfo(signPath);
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }

            string script = string.Empty;
            #region 保存上传
            if (Request.Method.EqualsIgnoreCase("post") && Request.Form.Files != null && Request.Form.Files.Count > 0)
            {
                var file = Request.Form.Files[0];
                if (file.Length > 0)
                {
                    string extname = Path.GetExtension(file.FileName);
                    if (extname.IsNullOrWhiteSpace() || (!extname.EqualsIgnoreCase(".gif") && !extname.EqualsIgnoreCase(".jpg") 
                        && !extname.EqualsIgnoreCase(".png")))
                    {
                        script = "alert('只能上传gif,jpg,png类型的图片文件!'); window.location = window.location;";
                        ViewData["script"] = script;
                        return null;
                    }
                    string filename = signPath + "/default.png";
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    Business.Log.Add("修改了签名", filename, Business.Log.Type.系统管理);
                    script = "alert('上传成功!'); window.location = window.location;";
                    ViewData["script"] = script;
                }
            }
            #endregion

            #region 恢复默认
            if (Request.Method.EqualsIgnoreCase("post") && !Request.Forms("reset").IsNullOrEmpty())
            {
                string filename = signPath + "/default.png";
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                    Business.Log.Add("恢复了签名", filename, Business.Log.Type.系统管理);
                }
                script = "alert('已恢复为默认签名!'); window.location = window.location;";
                ViewData["script"] = script;
            }
            #endregion

            if (!System.IO.File.Exists(signPath + "/default.png"))
            {
                var img = new Business.User().CreateSignImage(user.Name);
                img.Save(signPath + "/default.png", System.Drawing.Imaging.ImageFormat.Png);
            }
            string signSrc = Url.Content("~/RoadFlowResources/images/userSigns/" + user.Id.ToUpperString() + "/default.png");
            ViewData["signSrc"] = signSrc;
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [Validate]
        public IActionResult EditPass()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        /// <summary>
        /// 保存修改密码
        /// </summary>
        /// <returns></returns>
        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveEditPass()
        {
            string oldpass = Request.Forms("oldpass").Trim();
            string newpass = Request.Forms("newpass").Trim();
            string newpass1 = Request.Forms("newpass1").Trim();
            var user = Current.User;
            if (null == user)
            {
                return "未找到您的登录信息，请重新登录!";
            }
            if (!newpass.Equals(newpass1))
            {
                return "两次输入密码不一致!";
            }
            Business.User buser = new Business.User();
            if (!user.Password.Equals(buser.GetMD5Password(user.Id, oldpass)))
            {
                return "旧密码不正确!";
            }
            user.Password = buser.GetMD5Password(user.Id, newpass);
            buser.Update(user);
            return "密码修改成功!";
        }

        /// <summary>
        /// 个人信息
        /// </summary>
        /// <returns></returns>
        [Validate]
        public IActionResult Info()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View(Current.User);
        }

        /// <summary>
        /// 保存个人信息
        /// </summary>
        /// <returns></returns>
        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveInfo()
        {
            var user = Current.User;
            if (null == user)
            {
                return "未找到您的登录信息，请重新登录!";
            }
            user.Tel = Request.Forms("Tel");
            user.Mobile = Request.Forms("MobilePhone");
            user.Fax = Request.Forms("Fax");
            user.Email = Request.Forms("Email");
            user.QQ = Request.Forms("QQ");
            user.WeiXin = Request.Forms("WeiXin");
            user.OtherTel = Request.Forms("OtherTel");
            user.Note = Request.Forms("Note");
            new Business.User().Update(user);
            return "保存成功!";
        }

        /// <summary>
        /// 快捷菜单
        /// </summary>
        /// <returns></returns>
        public IActionResult Shortcut()
        {
            string menuhtml = string.Empty;
            Business.Menu bmenu = new Business.Menu();
            var user = Current.User;
            menuhtml = bmenu.GetMenuTreeTableHtml(string.Empty, user.Id);
            var shortcuts = new Business.UserShortcut().GetListByUserId(user.Id);
            ViewData["shortcuts"] = shortcuts;
            ViewData["shortcutJson"] = Newtonsoft.Json.JsonConvert.SerializeObject(shortcuts, Newtonsoft.Json.Formatting.None);
            ViewData["menuhtml"] = menuhtml;
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        /// <summary>
        /// 保存快捷菜单
        /// </summary>
        /// <returns></returns>
        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveShortcut()
        {
            string menuids = Request.Forms("menuid");
            Business.UserShortcut userShortcut = new Business.UserShortcut();
            Guid userId = Current.UserId;
            List<Model.UserShortcut> userShortcuts = new List<Model.UserShortcut>();
            int sort = 0;
            foreach (var menuid in menuids.Split(','))
            {
                if (!menuid.IsGuid(out Guid mid))
                {
                    continue;
                }
                Model.UserShortcut userShortcutModel = new Model.UserShortcut
                {
                    Id = Guid.NewGuid(),
                    MenuId = mid,
                    UserId = userId,
                    Sort = sort += 5
                };
                userShortcuts.Add(userShortcutModel);
            }
            userShortcut.Add(userShortcuts.ToArray(), userId);
            return "保存成功!";
        }

        /// <summary>
        /// 保存快捷菜单排序
        /// </summary>
        /// <returns></returns>
        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveShortcutSort()
        {
            string sorts = Request.Forms("sort");
            Business.UserShortcut userShortcut = new Business.UserShortcut();
            List<Model.UserShortcut> userShortcuts = new List<Model.UserShortcut>();
            int index = 0;
            foreach (string sort in sorts.Split(','))
            {
                if (!sort.IsGuid(out Guid sid))
                {
                    continue;
                }
                var model = userShortcut.Get(sid);
                if (null != model)
                {
                    model.Sort = index += 5;
                    userShortcuts.Add(model);
                }
            }
            userShortcut.Update(userShortcuts.ToArray());
            return "保存成功!";
        }

        /// <summary>
        /// 头像设置
        /// </summary>
        /// <returns></returns>
        public IActionResult UserHeader()
        {
            var user = Current.User;
            string headImg = string.Empty;
            if (!user.HeadImg.IsNullOrWhiteSpace())
            {
                if (System.IO.File.Exists(Current.WebRootPath + user.HeadImg))
                {
                    headImg = Url.Content(user.HeadImg);
                }
            }
            if (headImg.IsNullOrWhiteSpace())
            {
                headImg = Url.Content("~/RoadFlowResources/images/userHeads/default.jpg");
            }
            ViewData["headImg"] = headImg;
            return View();
        }

        /// <summary>
        /// 保存头像
        /// </summary>
        /// <returns></returns>
        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveUserHead()
        {
            string x = Request.Forms("x");
            string y = Request.Forms("y");
            string x2 = Request.Forms("x2");
            string y2 = Request.Forms("y2");
            string w = Request.Forms("w");
            string h = Request.Forms("h");
            string img = Current.ContentRootPath + "/Attachment/" + (Request.Forms("img") ?? "").DESDecrypt();
            var user = Current.User;
            if (img.IsNullOrEmpty() || !System.IO.File.Exists(img))
            {
                return "文件不存在!";
            }
            string headImg = Url.Content("~/RoadFlowResources/images/userHeads/" + user.Id.ToString("N") + "/" + Guid.NewGuid().ToString("N") + ".jpg");
            var issave = ImgHelper.CutAvatar(img, Current.WebRootPath + headImg, x.ToInt(), y.ToInt(), w.ToInt(), h.ToInt());
            if (user != null && issave)
            {
                user.HeadImg = headImg;
                new Business.User().Update(user);
                return "保存成功!";
            }
            return "保存失败!";
        }
    }
}